<?php

class SettingController extends Controller
{
	public function __construct($id,$module=null){
		parent::__construct($id,$module);
		$this->layout='application.views.layouts.setting';
	}
	
	public function filters()
    {
        return array(
            'accessControl',
        );
    }
	public function accessRules() {
		return array(
			array('allow','actions'=>array('bindResultAccount'),'users'=>array('*')),
			array('deny','expression'=>'$user->isGuest'),
		
		
		);
	}
	/**
	 * 个人资料
	 */
	public function actionIndex()
	{
	    $model = new UserinfoForm;

	    // if it is ajax validation request
		if(isset($_POST['ajax']) && $_POST['ajax']==='userinfo-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	    $user = User::model()->findByAttributes(array('_id'=>Yii::app()->user->uid));
		if(isset($_POST['UserinfoForm']))
		{
//			$model->attributes=$_POST['UserinfoForm'];
			
			$model->setAttributes($_POST['UserinfoForm'],false);
			// validate user input and redirect to the previous page if valid
			if($model->validate() ){
			    
			    $user->setAttributes($model->getAttributes(),false);
			    
//			    print_r($_POST['UserinfoForm']);
			    if($user->save()){
			        echo 'Save OK.';
			        $this->flash('保存成功。');
			    }
			     
			}
//				$this->redirect(Yii::app()->user->returnUrl);
		}else{
    	    
    	    $model->attributes = $user->getAttributes();
		}
	    
		$this->render('index',array('model'=>$model));
	}

	/**
	 * 更换头像
	 */
	public function actionPhoto(){
	    
	   
		$this->render('photo');
	}
	
	/**
	 * 更改密码
	 */
	public function actionChangePasswd(){
		
	   $model = new ChangePasswordForm('changePasswd');

	    // if it is ajax validation request
		if(isset($_POST['ajax']) && $_POST['ajax']==='changpassword-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
		if(isset($_POST['ChangePasswordForm']))
		{
			$model->attributes=$_POST['ChangePasswordForm'];
			// validate user input and redirect to the previous page if valid
			if($model->validate() ){

				$user = User::model()->findByUid(Yii::app()->user->uid); 
	    		if(md5($model->oldpassword) != $user->password){
	    			$model->addError('oldpassword',"原密码输入有误。");
 	    		}else{
					$user->password = md5($model->password);
				    if($user->save()){
				    	$model ->unsetAttributes();
				        $this->flash("密码修改成功！");
				    }
	    		}
			} 
//				$this->redirect(Yii::app()->user->returnUrl);
		}
		
		$this->render('changePasswd',array('model'=>$model));
	}

	
	/**
	 * 个性化域名
	 */
	public function actionCustomizeDomain(){
	
	    $model = new DomainForm;

	    // if it is ajax validation request
		if(isset($_POST['ajax']) && $_POST['ajax']==='domain-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	    $user = User::model()->findByPk( Yii::app()->user->uid);
		if(isset($_POST['DomainForm']))
		{
			$model->attributes=$_POST['DomainForm'];
			// validate user input and redirect to the previous page if valid
			if($model->validate() ){
			    
			    $user->setAttributes($model->getAttributes(),false);
			    
			    if($user->save()){
			        //echo 'Save OK.';
			    }
			     
			}
		}else{
    	    
    	    $model->attributes = $user->getAttributes();
		}
	    
		$this->render('customizeDomain',array('model'=>$model));
	}
	
	/**
	 * 
	 */
	public function actionWbRegister(){
		
		$model=new RegisterForm('wbregister');
		$user_id=Yii::app ()->user->getState ( 'uid');
    	
    	$user = User::model ()->findByUid ( $user_id );
		if (isset ( $_POST ['ajax'] ) && $_POST ['ajax'] === 'register-form') {
			echo CActiveForm::validate ( $model );
			Yii::app ()->end ();
		}
		if (isset ( $_POST ['RegisterForm'] )) {
			$model->attributes = $_POST ['RegisterForm'];
      
			// validate user input and redirect to the previous page if valid
			if ($model->validate () && $model->wbRegister ($user)) {
				Yii::app ()->user->setState ('me', (object ) $user->attributes  );
				@CEmailHelper::wellcome($model->email,$model->email);
				
				$loginForm = new LoginForm ();
				$loginForm->username = $model->email;
				$loginForm->password = $model->password;
				if (! $loginForm->login ()) {
					$this->redirect ( Yii::app ()->user->loginUrl );
				} else
					$this->redirect ( Yii::app ()->user->returnUrl );
			
			}
		}

		$this->render('wbregister',array('model'=>$model));
	}
	
	/**
	 * 绑定帐号
	 */
	public function actionAccount(){
		
		$binds = UserProvidor::findAllByUid(Yii::app()->user->uid);
		
		$unbindIds = array('P100');

		$this->render('account',array('data'=>compact('binds','unbindIds')));
	}
	
    public function actionBindAccount($pid = 'qq'){ 
//        $pa = func_get_arg(0);
//        print_r($pa);
//        print $providor ;
//        exit;
//        $providor = func_get_arg(0);
        $this->redirect(WeiboApiFactory::authorizeURL($pid));
	}
	public function actionBindResultAccount(){
	    if(!isset($_GET['pid']))
            		$this->redirect('/setting/account');
            		
	    if (isset($_GET['oauth_verifier'])) {
            $last_key = WeiboApiFactory::getAccessToken( $_GET['pid'],  $_GET['oauth_verifier']);
            //oauth_token    'oauth_token_secret' 
            if(isset($last_key['oauth_token'])){
            	
            		
                $pid = $_GET['pid'];
                
            	
                $up = new UserProvidor;
                
                $up->pid = $pid;
	            $up->uid = Yii::app()->user->uid ;
                $up->puid =$last_key['user_id'] ;
                $up->type = Providor::$AUTH_TYPE[$pid];
                $up->aKey = $last_key ['oauth_token'];
                $up->sKey = $last_key ['oauth_token_secret'];
                
                if($up->save()){
                     Yii::app()->user->setFlash('Acount_Msg','Bind OK.'.var_export($last_key,true));
                }
            
            //store
		    $this->redirect(array('setting/account'));
            }
           
        }else{
        	$this->redirect(array('setting/account'));
        }
		
//	    print_r($_SERVER);
//	    print_r($_GET);
//	    
	}
	// -----------------------------------------------------------
	// Uncomment the following methods and override them if needed
	/*
	public function filters()
	{
		// return the filter configuration for this controller, e.g.:
		return array(
			'inlineFilterName',
			array(
				'class'=>'path.to.FilterClass',
				'propertyName'=>'propertyValue',
			),
		);
	}

	public function actions()
	{
		// return external action classes, e.g.:
		return array(
			'action1'=>'path.to.ActionClass',
			'action2'=>array(
				'class'=>'path.to.AnotherActionClass',
				'propertyName'=>'propertyValue',
			),
		);
	}
	*/
}